package com.song.demo.webmvc.aop;

import java.lang.reflect.Method;

/**
 * 封装拦截器回调的通用逻辑，在mini版本中主要
 * 封装反射动态调用方法,其子类只需控制调用顺序即可
 */
public abstract  class GPAbstractAspectJAdvice implements GPAdvice {
    private Method aspectMethod;

    private Object aspectTarget;

    public GPAbstractAspectJAdvice(Method aspectMethod,Object aspectTarget){
        this.aspectMethod = aspectMethod;
        this.aspectTarget = aspectTarget;
    }
    //反射动态调用方法
    protected  Object invokeAdviceMethod(GPJoinPoint joinPoint,Object returnValue,Throwable ex)throws Throwable{
        Class<?>[] parameterTypes = this.aspectMethod.getParameterTypes();
        if (parameterTypes == null || parameterTypes.length == 0){
            return this.aspectMethod.invoke(aspectTarget);
        }else {
            Object[] args = new Object[parameterTypes.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                if (parameterTypes[i] == GPJoinPoint.class){
                    args[i] = joinPoint;
                }else if (parameterTypes[i] == Throwable.class){
                    args[i] = ex;
                }else if (parameterTypes[i] == Object.class){
                    args[i] = returnValue;
                }

            }
            return this.aspectMethod.invoke(aspectTarget,args);
        }

    }


}
